import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

public class LoginFrame extends JFrame {

    private static JTextField usernameField;

    public String getUserName() {
        return usernameField.getText();
    }

    public LoginFrame() {
        // 设置窗口标题
        setTitle("登录页面");

        // 设置窗口大小
        setSize(300, 200);

        // 设置窗口关闭操作
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 创建面板
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(3, 2));

        // 添加用户名标签和文本框
        JLabel usernameLabel = new JLabel("用户名:");
        usernameField = new JTextField();
        panel.add(usernameLabel);
        panel.add(usernameField);

        // 添加登录按钮
        JButton loginButton = getjButton();
        panel.add(new JLabel()); // 占位符
        panel.add(loginButton);

        // 将面板添加到窗口中
        add(panel);

        // 居中显示窗口
        setLocationRelativeTo(null);
    }

    public void sendmes(String name) throws IOException {
        String host; // 接受ip地址输入的字符串
        int port = 12000;// 服务器端口
        byte[] data;// 发送数据缓冲区
        DatagramPacket cPacket = null;
        DatagramSocket cSocket = null;
        InputStreamReader out = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(out);
        host = "127.0.0.1"; // 服务器ip
        InetAddress IPAddress = InetAddress.getByName(host);// 获取ip地址
        cSocket = new DatagramSocket(); // 创建DatagramSocket套接字
        data = (name + " " + 0 + " " + 0).getBytes(StandardCharsets.UTF_8);
        cPacket = new DatagramPacket(data, data.length, IPAddress, port);
        cSocket.send(cPacket);
    }

    private JButton getjButton() {
        JButton loginButton = new JButton("登录");
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 处理登录按钮点击事件
                String username = usernameField.getText();
                try {
                    sendmes(username);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }

                // 跳转
                Client client = new Client(username);
                client.setVisible(true);
                dispose();
            }
        });
        return loginButton;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new LoginFrame().setVisible(true);
            }
        });
    }
}
